#include <stdio.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <assert.h>
#include <fcntl.h>       
#include <unistd.h>
#include <sys/epoll.h>
#include <errno.h>

#define BUFFER_SIZE 1024
#define MAX_EVENTS 5

int setnonblocking(int fd){
	int old_option = fcntl(fd, F_GETFL);
	fcntl(fd, F_SETFL, old_option|O_NONBLOCK);
	return old_option;
}

void addfd(int epollfd, int fd){
	epoll_event event;
	event.events = EPOLLIN|EPOLLET;
	event.data.fd = fd;
	epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event);
	setnonblocking(fd);
}

int main(int argc, char const *argv[])
{	
	// if(argc!=3){
	// 	printf("Usage:%s, <ip> <port>\n",argv[0]);
	// 	exit(1);
	// }
	char buf[BUFFER_SIZE];  
	epoll_event events[MAX_EVENTS];
	const char* ip = "0.0.0.0";
	char* port = "9876";

	struct sockaddr_in serv_addr;
	bzero(&serv_addr, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	inet_pton(AF_INET, ip, &serv_addr.sin_addr);
	// serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	// printf("%s\n", inet_ntoa(serv_addr.sin_addr));
	serv_addr.sin_port = htons(atoi(port));

	int serv_sock = socket(PF_INET, SOCK_STREAM, 0);
	assert(serv_sock>=0);
	
	int ret;
	ret = bind(serv_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
	assert(ret>=0);	

	ret = listen(serv_sock, 5);
	assert(ret>=0);

	int epollfd = epoll_create(5);
	assert(epollfd != -1);

	addfd(epollfd, serv_sock);
	int user_count=0;
	while(1){
		ret = epoll_wait(epollfd, events, MAX_EVENTS, -1);
		if(ret<0){
			printf("epoll error");
			break;
		}
		for(int i=0; i<ret; i++){
			if(events[i].data.fd == serv_sock){
				// new connection
				struct sockaddr_in clnt_addr;
				socklen_t clnt_addr_size = sizeof(clnt_addr);
				int connfd = accept(serv_sock, (struct sockaddr*)&clnt_addr, &clnt_addr_size);
				assert(connfd>0);

				printf("Connected client %d \n", user_count+1);
				user_count++;

				addfd(epollfd, connfd);
			}
			else if(events[i].events && EPOLLIN){
				// reading socket
				while(1){
					memset(buf, '\0', BUFFER_SIZE);
					ret = recv(events[i].data.fd, buf, BUFFER_SIZE-1, 0);
					if(ret<0){
						if (errno == EAGAIN || (errno == EWOULDBLOCK))
							break; //非阻塞读，意味着读完了所有数据
						close(events[i].data.fd);
						printf("error, close connection\n");
						break;
					}
					else if(ret==0){
						// the connection terminated
						epoll_ctl(epollfd, EPOLL_CTL_DEL, events[i].data.fd, NULL);
						close(events[i].data.fd);
						printf("client %d closed\n", events[i].data.fd);
						break;
					}
					else{
						//  write back
						send(events[i].data.fd, buf, ret, 0);
					}
				}
			}
			else{
				printf("something else happened \n");
			}
		}
	}
	close(serv_sock);
	close(epollfd);
	return 0;
}